﻿using Newtonsoft.Json;
using SpaceNeedle.SDK.Windows.Platform.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;


namespace SpaceNeedle.x6473.WindowsPhone.Common
{
    public class WebRequest : WebRequestBase
    {
        private HttpClient GetHttpClient()
        {
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
            return httpClient;
        }

        public override async Task<HttpResponse<T>> DownloadStringAsync<T>(string uri, string method, Dictionary<string, string> headers, params string[] args)
        {
            HttpClient client = GetHttpClient();

            foreach (var header in headers)
            {
                client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }

            return await this.HttpRequest<T>(client, method, uri, null);
        }

        public override async Task<string> DownloadStringAsync(string uri, string method, params string[] args)
        {
            string data = string.Empty;

            if (args != null && args.Length > 1)
            {
                data = "{";

                for (int i = 0; i < args.Length; i++)
                {
                    data += @"""" + args[i] + @"""" + ":" + @"""" + args[++i] + @""",";
                }

                data += "}";

                data = data.Replace(",}", "}");
            }

            WebClient web = new WebClient();
            web.Headers["User-Agent"] = "WP8";
            web.Headers["Content-Type"] = "application/json";
            return await web.UploadStringTaskAsync(uri, data, method);
        }

        public async Task<string> DownloadStringAsync(string uri)
        {
            WebClient web = new WebClient();
            web.Headers["User-Agent"] = "WP8";

            return await web.DownloadStringTaskAsync(new Uri(uri));
        }

        public override async Task<HttpResponse<T>> DownloadApiStringAsync<T>(string uri, string method, Dictionary<string, string> headers, string httpContent, params string[] args)
        {
            string query = base.GetQuerystring(args);
            HttpClient client = GetHttpClient();

            HttpContent content = null;

            if (!string.IsNullOrEmpty(httpContent))
            {
                content = new StringContent(httpContent);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            return await this.HttpRequest<T>(client, method, uri + query, content);
        }

        public async Task<HttpResponse<T>> HttpRequest<T>(HttpClient httpClient, string method, string uri, HttpContent httpContent = null)
        {
            HttpResponse<T> result = new HttpResponse<T>();
            result.Status = -1;

            try
            {
                HttpResponseMessage response = null;

                switch (method.ToUpper())
                {
                    case "GET":
                        response = await httpClient.GetAsync(uri);
                        break;
                    case "POST":
                        response = await httpClient.PostAsync(uri, httpContent);
                        break;
                    case "PUT":
                        response = await httpClient.PutAsync(uri, httpContent);
                        break;
                    case "DELETE":
                        response = await httpClient.DeleteAsync(uri);
                        break;
                    default:
                        break;
                }

                string content = await response.Content.ReadAsStringAsync();

                try
                {
                    if (!string.IsNullOrEmpty(content))
                    {
                        result.Content = JsonConvert.DeserializeObject<T>(content);
                    }
                }
                catch { }

                result.Status = Convert.ToInt32(response.StatusCode);
                response.EnsureSuccessStatusCode();

            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }

            return result;
        }
    }
}
